package com.buaa.singlethreadfileload.service;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.buaa.singlethreadfileload.MainActivity;
import com.buaa.singlethreadfileload.bean.FileInfo;
import com.buaa.singlethreadfileload.bean.ThreadInfo;
import com.buaa.singlethreadfileload.db.ThreadDAO;
import com.buaa.singlethreadfileload.db.ThreadDAOImpl;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * Created by Administrator on 2016/5/15.
 */
public class DownLoadTask {
    private Context mContext;
    private FileInfo mFileInfo;
    private ThreadDAO mDao;
    private int mFinished=0;
    public boolean isPause=false;

    public DownLoadTask(Context mContext, FileInfo mFileInfo) {
        this.mContext = mContext;
        this.mFileInfo = mFileInfo;
        mDao=new ThreadDAOImpl(mContext);
    }

    public void downLoad(){
       //读取数据库的线程信息
        List<ThreadInfo> threads=mDao.getThreads(mFileInfo.getUrl());
        final ThreadInfo threadInfo;
        if (threads.size()==0){
            //当前线程为空线程，初始化线程信息对象
            threadInfo=new ThreadInfo(mFileInfo.getLength(),0,0,0,mFileInfo.getUrl());
        }else {
            //将最新的一条线程信息取出并付给当前threadInfo对象
            threadInfo=threads.get(0);
        }

        //创建子线程完成下载任务
        new Thread(){
            @Override
            public void run() {
                if (!mDao.isExists(threadInfo.getUrl(),threadInfo.getId())){
                    mDao.insertThread(threadInfo);
                }

                HttpURLConnection connection = null;
                RandomAccessFile randomAccessFile = null;//用于随机写入文件
                InputStream inputStream = null;

                try {
                    URL url=new URL(threadInfo.getUrl());
                    connection=(HttpURLConnection)url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("GET");
                    //设置下载位置
                    int start=threadInfo.getStart()+threadInfo.getFinished();
                   //设置随意位置写入文件的属性
                    connection.setRequestProperty("Range","bytes="+start+"-"+threadInfo.getEnd());
                   //设置文件写入位置
                    File file=new File(DownLoadService.DOWNLOAD_PATH,mFileInfo.getFileName());
                    randomAccessFile=new RandomAccessFile(file,"rwd");
                    randomAccessFile.seek(start);
                    Intent intent=new Intent();
                    intent.setAction(DownLoadService.ACTION_UPDATE);
                    mFinished+=threadInfo.getFinished();
                    //开始下载
                    if (connection.getResponseCode()==206){
                        //读取数据
                        inputStream=connection.getInputStream();
                        byte buf[]=new byte[1024*1024];
                        int len=-1;
                        long time=System.currentTimeMillis();
                        while ((len=inputStream.read(buf))!=-1){
                            //写入文件
                            randomAccessFile.write(buf,0,len);
                            //把下载的进度广播给Activity
                            mFinished+=len;
                            if (System.currentTimeMillis()-time>500){
                                time=System.currentTimeMillis();
                                //以百分比的形式显示前台进度条的进度
                                intent.putExtra("finished",mFinished*100/threadInfo.getEnd());
                                mContext.sendBroadcast(intent);
                                //在下载暂停时，保存下载进度
                                if (isPause){
                                    mDao.updateThread(threadInfo.getUrl(),threadInfo.getId(),mFinished);
                                    return;
                                }
                            }
                        }
                        //删除线程信息
                        mDao.deleteThread(threadInfo.getUrl(),threadInfo.getId());
                        MainActivity.mMainActivity.handler.sendEmptyMessage(0);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    try {
                        if (connection != null){
                            connection.disconnect();
                        }
                        if (randomAccessFile!=null){
                            randomAccessFile.close();
                        }
                        if (inputStream!=null){
                            inputStream.close();
                        }

                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
}
